package report_service

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io"
	"mime/multipart"
	"net/http"
	"path"
	"peilian-api/app/global/common"
	"peilian-api/app/global/errors"
	"peilian-api/app/global/log"
	"peilian-api/app/global/variable"
	"peilian-api/app/model"
	"peilian-api/utils/function"
	"peilian-api/utils/sdk"
	"peilian-api/utils/tools"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
)

type ReportService struct{}

// 图片美颜
func (iby *ReportService) GetImageBeauty(b64d string) (string, *errors.ErrRes) {
	params := map[string]string{"base64_data": b64d}
	reqData, _ := json.Marshal(params)
	resp, err := http.Post(
		variable.Config.Services.PicBeauty,
		"application/json",
		bytes.NewReader(reqData),
	)
	if err != nil {
		return b64d, errors.NewErrInfo(40001, fmt.Errorf("图片美颜接口调用失败: "+err.Error()))
	}
	if resp != nil {
		defer resp.Body.Close()
	}
	res := make(map[string]interface{})
	err = tools.ReadResponseBody(resp, &res)
	if err != nil {
		errMsg := "图片美颜响应结果解析失败" + err.Error()
		return b64d, errors.NewErrInfo(40002, fmt.Errorf(errMsg))
	}
	if code, _ := res["code"].(int64); code != 0 {
		errMsg := "图片美颜接口响应结果解析失败" + err.Error()
		return b64d, errors.NewErrInfo(40003, fmt.Errorf(errMsg))
	}
	ib64 := model.ImagesBase64{}
	b, _ := json.Marshal(res["data"])
	_ = json.Unmarshal(b, &ib64)
	return ib64.Base64Data, nil
}

func (iby *ReportService) GetImageBeautyByBinary(ctx *gin.Context) (string, *errors.ErrRes) {
	var base64Data string
	_, f, err := ctx.Request.FormFile("filename")
	if err != nil {
		return "", errors.NewErrInfo(20001, fmt.Errorf("图像数据获取失败, "+err.Error()))
	}

	f2, _ := f.Open()
	imgByte, _ := io.ReadAll(f2)
	// 上传图片
	go func() {
		defer tools.RecoverGoroutine()
		fileExt := strings.ToLower(path.Ext(f.Filename))
		fileName := function.CreateMD5(fmt.Sprintf("%s", time.Now().String())) + fileExt
		filePath := common.PhotoPath + fileName
		sdk.IOput(imgByte, filePath, "")
		log.Logger.InfoF(ctx, "filePath:"+filePath)
	}()
	base64Data = base64.StdEncoding.EncodeToString(imgByte)

	// 创建一个表单
	buf := new(bytes.Buffer)
	writer := multipart.NewWriter(buf)
	contentType := writer.FormDataContentType()
	formFile, err := writer.CreateFormFile("file", "new.jpg")
	if err != nil {
		return base64Data, errors.NewErrInfo(20001, fmt.Errorf("图像数据获取失败, "+err.Error()))
	}
	_, err = io.Copy(formFile, bytes.NewReader(imgByte))
	if err != nil {
		return base64Data, errors.NewErrInfo(20001, fmt.Errorf("图像数据获取失败, "+err.Error()))
	}
	writer.Close() // 发送之前必须调用Close()以写入结尾行
	resp, err := http.Post(variable.Config.Services.PicBeauty, contentType, buf)
	if err != nil {
		return base64Data, errors.NewErrInfo(20001, fmt.Errorf("post请求失败, "+err.Error()))
	}
	if resp != nil {
		defer resp.Body.Close()
	}
	res := make(map[string]interface{})
	err = tools.ReadResponseBody(resp, &res)
	if err != nil {
		errMsg := "图片美颜响应结果解析失败" + err.Error()
		return base64Data, errors.NewErrInfo(40002, fmt.Errorf(errMsg))
	}
	if code, _ := res["code"].(int64); code != 0 {
		errMsg := "图片美颜接口响应结果解析失败" + err.Error()
		return base64Data, errors.NewErrInfo(40003, fmt.Errorf(errMsg))
	}
	ib64 := model.ImagesBase64{}
	b64d, _ := json.Marshal(res["data"])
	_ = json.Unmarshal(b64d, &ib64)
	return ib64.Base64Data, nil
}
